import axios from 'axios'

const API_URL = '/api'

const state = {
  pets: [],
  pet: null,
  pagination: {
    total: 0,
    page: 1,
    limit: 10,
    totalPages: 0
  },
  filters: {
    category_id: null,
    gender: null,
    size: null,
    is_adopted: false
  }
}

const mutations = {
  SET_PETS(state, { pets, pagination }) {
    state.pets = pets
    state.pagination = pagination
  },
  SET_PET(state, pet) {
    state.pet = pet
  },
  SET_FILTERS(state, filters) {
    state.filters = { ...state.filters, ...filters }
  },
  RESET_FILTERS(state) {
    state.filters = {
      category_id: null,
      gender: null,
      size: null,
      is_adopted: false
    }
  },
  SET_PAGE(state, page) {
    state.pagination.page = page
  },
  ADD_PET(state, pet) {
    state.pets.unshift(pet)
  },
  UPDATE_PET(state, updatedPet) {
    const index = state.pets.findIndex(p => p.id === updatedPet.id)
    if (index !== -1) {
      state.pets.splice(index, 1, updatedPet)
    }
    if (state.pet && state.pet.id === updatedPet.id) {
      state.pet = updatedPet
    }
  },
  REMOVE_PET(state, petId) {
    state.pets = state.pets.filter(p => p.id !== petId)
    if (state.pet && state.pet.id === petId) {
      state.pet = null
    }
  }
}

const actions = {
  // 获取宠物列表
  async fetchPets({ commit, state, dispatch }, searchQuery) {
    try {
      dispatch('setLoading', true, { root: true })
      
      const { page, limit } = state.pagination
      const { category_id, gender, size, is_adopted } = state.filters
      
      // 构建查询参数
      const params = { page, limit }
      if (category_id) params.category_id = category_id
      if (gender) params.gender = gender
      if (size) params.size = size
      if (is_adopted !== null) params.is_adopted = is_adopted
      
      // 添加搜索查询参数
      if (searchQuery) {
        params.q = searchQuery
      }
      
      const response = await axios.get(`${API_URL}/pets`, { params })
      
      commit('SET_PETS', {
        pets: response.data.pets,
        pagination: response.data.pagination
      })
      
      return response.data.pets
    } catch (error) {
      const errorMessage = error.response ? error.response.data.message : error.message
      dispatch('setError', errorMessage, { root: true })
      return []
    } finally {
      dispatch('setLoading', false, { root: true })
    }
  },
  
  // 按类别获取宠物
  async fetchPetsByCategory({ commit, dispatch }, { categoryId, page = 1, limit = 10 }) {
    try {
      dispatch('setLoading', true, { root: true })
      
      const params = { page, limit }
      
      const response = await axios.get(`${API_URL}/pets/category/${categoryId}`, { params })
      
      commit('SET_PETS', {
        pets: response.data.pets,
        pagination: response.data.pagination
      })
      
      return response.data.pets
    } catch (error) {
      const errorMessage = error.response ? error.response.data.message : error.message
      dispatch('setError', errorMessage, { root: true })
      return []
    } finally {
      dispatch('setLoading', false, { root: true })
    }
  },
  
  // 获取单个宠物详情
  async fetchPet({ commit, dispatch }, petId) {
    try {
      dispatch('setLoading', true, { root: true })
      
      const response = await axios.get(`${API_URL}/pets/${petId}`)
      
      commit('SET_PET', response.data)
      return response.data
    } catch (error) {
      const errorMessage = error.response ? error.response.data.message : error.message
      dispatch('setError', errorMessage, { root: true })
      return null
    } finally {
      dispatch('setLoading', false, { root: true })
    }
  },
  
  // 设置过滤器
  setFilters({ commit, dispatch }, filters) {
    commit('SET_FILTERS', filters)
    commit('SET_PAGE', 1) // 重置到第一页
    dispatch('fetchPets')
  },
  
  // 重置过滤器
  resetFilters({ commit, dispatch }) {
    commit('RESET_FILTERS')
    commit('SET_PAGE', 1)
    dispatch('fetchPets')
  },
  
  // 翻页
  setPage({ commit, dispatch }, page) {
    commit('SET_PAGE', page)
    dispatch('fetchPets')
  },
  
  // 添加宠物（管理员）
  async addPet({ commit, dispatch, rootGetters }, petData) {
    try {
      dispatch('setLoading', true, { root: true })
      
      // 使用FormData处理文件上传
      const formData = new FormData()
      
      // 添加文本字段
      Object.keys(petData).forEach(key => {
        if (key !== 'image') {
          formData.append(key, petData[key])
        }
      })
      
      // 添加图片文件（如果有）
      if (petData.image) {
        formData.append('image', petData.image)
      }
      
      const config = {
        headers: {
          'x-auth-token': rootGetters['auth/currentUser'].token,
          'Content-Type': 'multipart/form-data'
        }
      }
      
      const response = await axios.post(`${API_URL}/pets`, formData, config)
      
      commit('ADD_PET', response.data)
      return response.data
    } catch (error) {
      const errorMessage = error.response ? error.response.data.message : error.message
      dispatch('setError', errorMessage, { root: true })
      return null
    } finally {
      dispatch('setLoading', false, { root: true })
    }
  },
  
  // 更新宠物（管理员）
  async updatePet({ commit, dispatch, rootGetters }, { petId, petData }) {
    try {
      dispatch('setLoading', true, { root: true })
      
      // 使用FormData处理文件上传
      const formData = new FormData()
      
      // 添加文本字段
      Object.keys(petData).forEach(key => {
        if (key !== 'image') {
          formData.append(key, petData[key])
        }
      })
      
      // 添加图片文件（如果有）
      if (petData.image) {
        formData.append('image', petData.image)
      }
      
      const config = {
        headers: {
          'x-auth-token': rootGetters['auth/currentUser'].token,
          'Content-Type': 'multipart/form-data'
        }
      }
      
      const response = await axios.put(`${API_URL}/pets/${petId}`, formData, config)
      
      commit('UPDATE_PET', response.data)
      return response.data
    } catch (error) {
      const errorMessage = error.response ? error.response.data.message : error.message
      dispatch('setError', errorMessage, { root: true })
      return null
    } finally {
      dispatch('setLoading', false, { root: true })
    }
  },
  
  // 删除宠物（管理员）
  async deletePet({ commit, dispatch, rootGetters }, petId) {
    try {
      dispatch('setLoading', true, { root: true })
      
      const config = {
        headers: {
          'x-auth-token': rootGetters['auth/currentUser'].token
        }
      }
      
      await axios.delete(`${API_URL}/pets/${petId}`, config)
      
      commit('REMOVE_PET', petId)
      return true
    } catch (error) {
      const errorMessage = error.response ? error.response.data.message : error.message
      dispatch('setError', errorMessage, { root: true })
      return false
    } finally {
      dispatch('setLoading', false, { root: true })
    }
  }
}

const getters = {
  getPets: state => state.pets,
  getPet: state => state.pet,
  getPagination: state => state.pagination,
  getFilters: state => state.filters,
  getAvailablePets: state => state.pets.filter(pet => !pet.is_adopted)
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
} 